package com.xiaoq.push.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaoq.coms.util.IdGenerator;
import com.xiaoq.push.entity.MessageEntity;
import com.xiaoq.push.entity.MsgCatalogueEntity;
import com.xiaoq.push.entity.TargetUserDTO4ReceiveMsg;
import com.xiaoq.push.vo.MessageSenderVo;
import com.xiaoq.users.entity.UserEntity;
import com.xiaoq.users.repository.UserRepository;
import com.xiaoq.vo.PagingVo;

@Service
public class PushMessageService {

	@Autowired
	private Datastore datastore;

	@Autowired
	private IdGenerator idGenerator;

//	@Autowired
//	MiPushServerService miPushServerService;

	@Autowired
	JdPushService jdPushService;

	@Autowired
	private UserRepository userRep;

	@Autowired
	private MsgCatalogueService msgCatalogueService;

	private static final Logger LOG = LoggerFactory.getLogger(PushMessageService.class);

	/**
	 * 查询某个用户某个目录下最后一条接收的信息
	 * 
	 * @param userId
	 * @param msgCatalogueCode
	 * @return
	 */
	public MessageEntity findLastMessageOfUserByMsgCatalogueCode(String userId, String msgCatalogueCode) {
		Query<MessageEntity> userMessageEntityQuery = datastore.createQuery(MessageEntity.class);
		userMessageEntityQuery.filter("targetUserDTOs.userId", userId).filter("msgCatalogueCode", msgCatalogueCode + "")
				.order("-createdAt");
		List<MessageEntity> messageEntityList = userMessageEntityQuery.asList();
		if (messageEntityList != null && messageEntityList.size() > 0) {
			return messageEntityList.get(0);
		} else {
			return null;
		}

	}

	/**
	 * 群发一条信息
	 * @param messageEntity
	 * @return
	 */
	public boolean createMsgAndSendToXiaomi(MessageEntity messageEntity) {
		
		List<TargetUserDTO4ReceiveMsg> targetUserDTOs = messageEntity.getTargetUserDTOs();
		List<String> androidUser_regIds = new ArrayList<>();
        List<String> iosUser_regIds = new ArrayList<>();
        MsgCatalogueEntity msgCatalogue = msgCatalogueService.getMsgCatalogue(messageEntity.getMsgCatalogueCode());
		String msgCatalogueName = msgCatalogue.getMsgCatalogueName();
		String msgThumbnailUrl = msgCatalogue.getThumbnailUrl();

		messageEntity.setMsgCatalogueName(msgCatalogueName);
		messageEntity.setMsgThumbnailUrl(msgThumbnailUrl);
		MessageSenderVo messageSenderVo = new MessageSenderVo();
		
		BeanUtils.copyProperties(messageEntity, messageSenderVo);
		
        for (TargetUserDTO4ReceiveMsg targetUserDTO : targetUserDTOs) {
            if (targetUserDTO.getMainOsType().equals("iOS")) {
                iosUser_regIds.add(targetUserDTO.getRegId());
            } else if (targetUserDTO.getMainOsType().equals("Android")) {
                androidUser_regIds.add(targetUserDTO.getRegId());
            }
        }
        
        try {
            if (iosUser_regIds.size() > 0) {
            	jdPushService.sendMessageToMultiIOSUsers(messageSenderVo,iosUser_regIds,true);
            }
            if (androidUser_regIds.size() > 0) {
            	jdPushService.sendMessageToMultiAndroidUsers(messageSenderVo, androidUser_regIds);
            }

            messageEntity.setId(idGenerator.nextId());
            datastore.save(messageEntity);
            return true;

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);

        }
		
	}
	
	public List<MessageEntity> findPagingMessagesOfUserByMsgCatalogueCode(String userId,Integer msgCatalogueCode,PagingVo pvo){
		int ps = pvo.getPs();
		int pn = (pvo.getPn() - 1) * ps;
		
		Query<MessageEntity> userMessageEntityQuery = datastore.createQuery(MessageEntity.class);
		
		userMessageEntityQuery.filter("targetUserDTOs.userId", userId);
        if(msgCatalogueCode!=null){
        	userMessageEntityQuery.filter("msgCatalogueCode", msgCatalogueCode+"");
        }
        userMessageEntityQuery.order("-createdAt");
		Long total = 0L;
		List<MessageEntity> messageList = new ArrayList<>();
		total = (long) userMessageEntityQuery.asList().size();
		userMessageEntityQuery.offset(pn).limit(ps);
		pvo.setTc(total);
		messageList = userMessageEntityQuery.asList();

		return messageList;
		
	}
	
	/**
	 * 给c端用户发布一条信息
	 * @param userId
	 * @param catalogueCode
	 * @param msgTitle
	 * @param msgContent
	 * @param mesTarId
	 * @param mesType
	 * @param cornershopId
	 * @return
	 */
	public boolean sendMessageToXiaomi(String userId, String catalogueCode, String msgTitle, String msgContent,String mesTarId,String mesType,String cornershopId, String mesUrl, boolean mutable_content) {

		UserEntity user = userRep.getById(userId);

		if(user==null || user.getTermDevice()==null || StringUtils.isBlank(user.getTermDevice().getRegId())
				|| StringUtils.isBlank(user.getTermDevice().getOsType())){
			return false;
		}

		String regId = user.getTermDevice().getRegId();
		String osType = user.getTermDevice().getOsType();
		MsgCatalogueEntity msgCatalogue = msgCatalogueService.getMsgCatalogue(catalogueCode);
		String msgCatalogueName = msgCatalogue.getMsgCatalogueName();
		String msgThumbnailUrl = msgCatalogue.getThumbnailUrl();
		
		MessageEntity message = new MessageEntity();
		List<TargetUserDTO4ReceiveMsg> targetUserDTOs = new ArrayList<>();
		TargetUserDTO4ReceiveMsg targetUser = new TargetUserDTO4ReceiveMsg();
		targetUser.setUserId(userId);
		targetUser.setRegId(regId);
		targetUser.setMainOsType(osType);
		targetUserDTOs.add(targetUser);
		
		message.setTargetUserDTOs(targetUserDTOs);
		
		message.setMesTarId(mesTarId);
		message.setMesType(mesType);
		message.setMsgTitle(msgTitle);
		message.setMsgContent(msgContent);
		message.setMsgCatalogueCode(catalogueCode);
		message.setMsgThumbnailUrl(msgThumbnailUrl);
		message.setMsgCatalogueName(msgCatalogueName);
		message.setCornershopId(cornershopId);
		message.setMesUrl(mesUrl);
		
		MessageSenderVo messageSenderVo = new MessageSenderVo();
		
		BeanUtils.copyProperties(message, messageSenderVo);
		message.setId(idGenerator.nextId());
		datastore.save(message);
		
		LOG.info("类型"+osType);
		if (StringUtils.equalsIgnoreCase(osType, "Android")) {
			try {
				jdPushService.sendMessageToSingleAndroidUser(messageSenderVo, regId);
				LOG.info("极光推送到android的信息标题："+msgTitle);
				return true;
			} catch (Exception e) {

				LOG.error("发送android设备信息失败！", e);
			}
		} else if (StringUtils.equalsIgnoreCase(osType, "iOS")) {
			try {
				jdPushService.sendMessageToSingleIOSUser(messageSenderVo, regId,mutable_content);
				LOG.info("极光推送到iOS的信息标题："+msgTitle);
				return true;
			} catch (Exception e) {
				LOG.error("发送IOS设备信息失败！", e);
				e.printStackTrace();
			}
		}
		return false;

	}

}
